package cc.ufinity.networkdiagnose.widget;
 
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.view.R;

public class FilesUploadWidget extends GeneralTestWidget implements View.OnClickListener {
   
    private Activity ctx;
    private Button btnSave;
    private Button btnBack; 
    private List<String[]> filesList ;
    private File fileDir ;
    private final static String FILE_TYPE_XML="xmlfile";
    private final static String FILE_TYPE_IMAGE="imagefile";
	private String localPath ;
	private Handler handler;
	private int successNum=0;
	private int current;
	private boolean progressing = false;
	
	private FtpTestManager fm;
	
    public FilesUploadWidget(Activity context) {
        super(context);
        this.ctx = context;
        inflate(context, R.layout.upload_files, this);
        btnSave = (Button) this.findViewById(R.id.btn_upload_save);
        btnBack = (Button) this.findViewById(R.id.btn_upload_back); 
        btnSave.setOnClickListener(this);
        btnBack.setOnClickListener(this); 
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					dismissMessageDialog();
					progressing = true;
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				case MessageWhat.WIFI_SUCESS_CONNECTED:  
					dismissMessageDialog();
                	start();
                    break; 
				case MessageWhat.FTP_UPLOAD_DONE:
					progressing = true;
		    		showMessage(ctx, "成功上传"+successNum+"个测试结果");
		    	    dismissProgressDialog();
		    	    if(fm != null) {
		    	    	fm.logout();
		    	    }
		    		break;
				case MessageWhat.FTP_UPLOAD_TASK_DONE:
					progressing = false;
					current++;
					successNum ++;
					progressDialog.setProgress(current);
                    showMessage(ctx, "第"+current+"个结果上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
					progressing = false;
					current++; 
					progressDialog.setProgress(current);
                    showMessage(ctx, "第"+current+"个结果上传失败");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissProgressDialog();
                    progressing = true;
                    showMessage(ctx, "FTP登录失败，请检查网络是否连接.");
                    break;
				}
			}
		};
    
    }

    private void start() {
    	current = 0;
    	progressing = false;
    	fileDir = ctx.getFilesDir();
 		localPath = fileDir.getParent()+ File.separator + "wlantest" + File.separator  ;
 		if (localPath!=null) {
 	        filesList = listFilesName(localPath);
 		}
    	if(filesList!=null && filesList.size()!=0){
    	    showProgressDialog(ctx, "正在文件上传中...",filesList.size()); 
    	    Thread thread = new Thread(){
    	    	@Override
    	    	public void run(){
    	    		while (current>=0 && current < filesList.size()&& !progressing) {
    	    			progressing = true;
    	    			String[] tempStrings = filesList.get(current);
    	    	    	if (tempStrings!=null) {
    	    	    		if(tempStrings[0]!=null && tempStrings[0].contains(".xml"))
    	    	    			if(!upload(tempStrings[0],FILE_TYPE_XML)) {
    	    	    				Message msg = new Message(); 
    	    						msg = handler.obtainMessage();
    				                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
    				                msg.sendToTarget();
    	    	    				//return;
    	    	    			} else if (tempStrings[0]!=null && tempStrings[0].contains(".jpg")) 
	    	    	    			if(!upload(tempStrings[0],FILE_TYPE_IMAGE)) {
	    	    	    				Message msg = new Message(); 
	    	    						msg = handler.obtainMessage();
	    				                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
	    				                msg.sendToTarget();
	    	    	    				//return;
	    	    	    			}
    					} else {
    						Message msg = new Message(); 
    						msg = handler.obtainMessage();
			                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
			                msg.sendToTarget();
						}
    	    	    	if (current == filesList.size()) {
    	    	    		try {
								Thread.sleep(100);
							} catch (InterruptedException e) {}
        	    			Message msg = new Message(); 
    						msg = handler.obtainMessage();
    		                msg.what = MessageWhat.FTP_UPLOAD_DONE;
    		                msg.sendToTarget();
    					}
					}
    	    		
    	    	}
    	    };
    	    thread.start();
    	} else {
			showMessage(ctx, "暂无未上传测试结果");  
		}
    } 
    
    //文件上传
	public boolean upload(String fileName,String fileType) { 
        Message msg = null;
        boolean success = false;
        DBManager db = new DBManager(ctx);
        FTPConfig ftp = db.getFtp2();
        db.release();
//        if (ftp == null) {
//            msg = handler.obtainMessage();
//            msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
//            msg.sendToTarget();
//            return success;
//        } 
        String remotePath = "/";
        int port = ftp.port;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        if(fileType.equals(FILE_TYPE_IMAGE)) {        	
        	remotePath = remotePath + "UpImages/"; 
        } 
        //直接上传到ftp根目录，2013-3-5修改
//        else {
//        	remotePath = remotePath + formatter.format(curDate) + "/";
//        }
        fm = new FtpTestManager(localPath, remotePath, fileName);
//            fm.setCtx(ctx);
        if (fm.login(ftp.address, port, ftp.userName, ftp.password)) {
            if (fm.upload() > 0) {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_TASK_DONE;
                msg.sendToTarget();
                fm.logout();
                File file = new File(localPath + fileName);
                if (file.exists()) {
                    file.delete();
                }
                success = true;
            }/* else {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
                msg.sendToTarget();
            }*/
        } else {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_LOGIN_FAILED;
            msg.sendToTarget();
        }
        return success;
    } 
        
    //获取所有测试结果文件名和路径
    private List<String[]> listFilesName(String folderPath) { 
    	List<String[]> filesList = new ArrayList<String[]>();
    	File file = new File(folderPath); 
	     // 文件
	    if (!file.isDirectory()) {  
	    	return filesList;
	    } else if (file.isDirectory()) { // 如果是目录， 遍历所有子目录取出所有文件名 
	    	  String[] filelist = file.list(); 
	    	  for (int i = 0; i < filelist.length; i++) { 
		    	    File readfile = new File(folderPath + "/" + filelist[i]); 
		    	    if (!readfile.isDirectory()) {
		    	    	String[] tempStrings = new String[2];
		    	    	tempStrings[0] =  filelist[i];
		    	    	tempStrings[1] = folderPath;
		    	    	filesList.add(tempStrings);
		    	    } else if (readfile.isDirectory()) { // 子目录的目录
		    	    } 
	    	   } 
	    }  
    	return filesList;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_upload_save:
            start();
            break;
        case R.id.btn_upload_back:
            this.backToConfig(ctx);
            break;
        }
    }

    
}
